package com.jasmine.bjstkserver.server.article;

import cn.hutool.core.util.StrUtil;
import com.jasmine.bjstkserver.manager.os.OsManager;
import com.jasmine.bjstkserver.mapper.ArticleDraftLogMapper;
import com.jasmine.bjstkserver.mapper.ArticleDraftMapper;
import com.jasmine.bjstkserver.server.article.draft.model.ArticleDraftEntity;
import com.jasmine.bjstkserver.server.article.draft.model.ArticleDraftRes;
import com.jasmine.bjstkserver.server.article.online.model.ArticleReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author : jasmineXz
 */
@RestController
@RequestMapping("/scheduled/article")
public class ArticleScheduled {
    private static final Logger log = LoggerFactory.getLogger(ArticleScheduled.class);

    @Autowired
    private ArticleDraftMapper articleDraftMapper;

    @Autowired
    private ArticleDraftLogMapper articleDraftLogMapper;

    @Autowired
    private OsManager osManager;

    /**
     * 每两小时执行备份
     * 文章改名会作为新文章备份
     * @throws IOException 文章写入流
     */
    @RequestMapping
    @Scheduled(cron="0 0 0/2 * * ?")
    public void toOs () throws IOException {
        log.info("[BJSTK] 开始备份文章");
        List<ArticleDraftRes> articleList = articleDraftMapper.findAll(new ArticleReq());
        for (ArticleDraftRes article : articleList) {
            // 文章内容为空不需要备份
            if (StrUtil.isBlank(article.getContentMd())) {
                continue;
            }
            // 文章版本与云端版本相同不需要备份
            if (article.getVersion().equals(article.getVersionCloud())) {
                continue;
            }
            try (InputStream is = new ByteArrayInputStream(article.getContentMd().getBytes(StandardCharsets.UTF_8))) {
                osManager.putAsync (
                    is,
                    String.format("%s/%s_%s.%s", "article", article.getUserId(), article.getName(), "md"),
                    article.getUserId()
                );
            }
            ArticleDraftEntity upd = new ArticleDraftEntity();
            upd.setArticleId(article.getArticleId());
            upd.setVersionCloud(article.getVersion());
            articleDraftMapper.updateByPrimaryKeySelective(upd);
        }
    }

    @DeleteMapping
    @Scheduled(cron="0 0 1 * * ?")
    public void deleteOutdated () {
        articleDraftLogMapper.deleteOutdated();
        log.info("[BJSTK] 删除 [14] 日前且条数大于 [20] 的文章记录");
    }

}
